<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;
class User extends BaseController {
    public function index() {
    }

    public function update() {
    // 获取 Bearer Token
    $token = Request::header('Authorization');
    if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
        return json(['code' => 401, 'msg' => '未授权访问']);
    }
    
    $token = $matches[1];
    $user = Db::name('think_users')->where('token', $token)->find();
    if (!$user) {
        return json(['code' => 401, 'msg' => 'token无效']);
    }

    // 验证参数
    $params = Request::post();
    
    $validate = Validate::rule([
        'avatar' => function($value) {
            if (empty($value)) return true;
            if (!is_string($value)) return false;
            return str_starts_with(strtolower($value), 'http');
        },
        'nickName' => function($value) {
            if (empty($value)) return true;
            if (!is_string($value)) return false;
            return mb_strlen($value) <= 20;
        },
        'sex' => function($value) {
            if (empty($value)) return true;
            if (!is_numeric($value)) return false;
            $value = (int)$value;
            return in_array($value, [1, 2]);
        },
        'birthYear' => function($value) {
            if (empty($value)) return true;
            if (!is_numeric($value)) return false;
            $value = (int)$value;
            return $value >= 1970 && $value <= (int)date('Y');
        },
        'location' => function($value) {
            if (empty($value)) return true;
            // Check if it's already an array/object
            if (is_array($value)) {
                return true;
            }
            // If it's a string, try to decode it
            if (!is_string($value)) return false;
            $decoded = json_decode($value, true);
            return json_last_error() === JSON_ERROR_NONE && is_array($decoded);
        },
        'apnsToken' => function($value) {
            if (empty($value)) return true;
            return is_string($value);
        }
    ]);

    if (!$validate->check($params)) {
        return json(['code' => 400, 'msg' => $validate->getError()]);
    }

    try {
        Db::startTrans();
        
        $updateData = [
            'update_time' => date('Y-m-d H:i:s')
        ];

        // 只更新提供的字段
        if (isset($params['avatar'])) {
            $updateData['avatar'] = $params['avatar'];
        }
        if (isset($params['nickName'])) {
            $updateData['nickname'] = $params['nickName'];
        }
        if (isset($params['sex'])) {
            $updateData['gender'] = $params['sex'];
        }
        if (isset($params['birthYear'])) {
            $updateData['birthday'] = $params['birthYear'] . '-01-01';
        }
        if (isset($params['location']) && is_array($params['location'])) {
            $updateData['location'] = json_encode($params['location'], JSON_UNESCAPED_UNICODE);
        }
        if (isset($params['apnsToken'])) {
            $updateData['apns_token'] = $params['apnsToken'];
        }
        if (isset($params['bio'])) {
            $updateData['bio'] = $params['bio'];
        }

        Db::name('think_users')
            ->where('id', $user['id'])
            ->update($updateData);

        Db::commit();
        return json([
            'code' => 200, 
            'msg' => '更新成功',
            'data' => $updateData
        ]);
    } catch (\Exception $e) {
        Db::rollback();
        return json(['code' => 500, 'msg' => '更新失败：' . $e->getMessage()]);
    }
}

    public function toggleBlacklist() {
    // 获取 Bearer Token
    $token = Request::header('Authorization');
    if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
        return json(['code' => 401, 'msg' => '未授权访问']);
    }
    $token = $matches[1];
    $user = Db::name('think_users')->where('token', $token)->find();
    if (!$user) {
        return json(['code' => 401, 'msg' => 'token无效']);
    }
    $validate = Validate::rule([
        'blocked_user_id' => 'require|integer',
    ]);
    $params = Request::post();
    if (!$validate->check($params)) {
        return json(['code' => 400, 'msg' => $validate->getError()]);
    }
    try {
        $blockedUserId = $params['blocked_user_id'];
        $existingRecord = Db::name('think_blacklist')
            ->where('user_id', $user['id'])
            ->where('blocked_user_id', $blockedUserId)
            ->find();
        if ($existingRecord) {
            Db::name('think_blacklist')
                ->where('user_id', $user['id'])
                ->where('blocked_user_id', $blockedUserId)
                ->delete();
            return json(['code' => 200, 'msg' => '取消拉黑成功', 'data'=>false]);
        } else {
            $data = [
                'user_id' => $user['id'],
                'blocked_user_id' => $blockedUserId,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
            ];
            Db::name('think_blacklist')->insert($data);
            return json(['code' => 200, 'msg' => '拉黑成功', 'data'=>true]);
        }
    } catch (\Exception $e) {
        return json(['code' => 500, 'msg' => '操作失败：' . $e->getMessage()]);
    }
    }

    //获取用户profile
    public function simpleProfile() {
        // 获取 Bearer Token
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        
        $token = $matches[1];
        
        try {
            // 获取用户信息
            $user = Db::name('think_users')
                ->field([
                    'nickname',
                    'avatar',
                    'gender',
                    'birthday',
                    'location',
                    'uuid',
                    'is_vip',
                    'vip_expire_date',
                    'score',
                    "bio"
                ])
                ->where('token', $token)
                ->find();
                
            if (!$user) {
                return json(['code' => 401, 'msg' => 'token无效']);
            }
            
            // 处理 location 数据
            if ($user['location']) {
                $user['location'] = json_decode($user['location'], true);
            }
            
            // 格式化返回数据
            $result = [
                'nickName' => $user['nickname'],
                'avatar' => $user['avatar'],
                'gender' => (int)$user['gender'],  // 0:未知 1:男 2:女
                'birthday' => $user['birthday'],
                'location' => $user['location'] ?: null,
                'uuid' => $user['uuid'],
                'isVip'=> $user['is_vip'],
                'vipExpireDate'=> $user['vip_expire_date'],
                "bio"=> $user['bio'] ?: null,
                'score' => (int)$user['score']  // 确保分数是整数
            ];
            
            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => $result
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '服务器错误：' . $e->getMessage()
            ]);
        }
    }
}